package com.lcy.web.model.sql.base.mine;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.DbKit;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.dialect.Dialect;
import com.jfinal.plugin.activerecord.dialect.MysqlDialect;
import com.lcy.web.utils.CommonUtils;

import java.util.List;
import java.util.Map;

/**
 * Created by loucunyin on 2016/12/5 0005.
 * 封装一些常用的操作
 */
@SuppressWarnings("rawtypes")
public abstract class BaseModel<M extends BaseModel<M>> extends Model<M> {
    private static final long serialVersionUID = -7995590145368349113L;

    protected SqlTemplate mSqlTemplate;
    protected String[] mSecretColumns;

    public BaseModel() {
        super();
        Dialect dialect = DbKit.getConfig().getDialect();
        if (dialect instanceof MysqlDialect) {
            mSqlTemplate = new MySqlTemplate(getTableName());
        } else {
            throw new RuntimeException("no sql dialect support");
        }
    }

    public Map<String, Object> getMap() {
        Map<String, Object> map = getAttrs();

        // 隐藏字段信息
        if (CommonUtils.checkArray(mSecretColumns)) {
            for (String name : mSecretColumns) {
                map.put(name, null);
            }
        }

        return map;
    }

    public abstract String getTableName();

    public SqlTemplate getSqlTemplate() {
        return mSqlTemplate;
    }

    public void setSqlTemplate(SqlTemplate sqlTemplate) {
        mSqlTemplate = sqlTemplate;
    }

    public List<M> findByColumn(String column, Object value) {
        String sql = mSqlTemplate.selectByColumn(column, value);
        return find(sql);
    }

    public M findFirstByColumn(String column, Object value) {
        String sql = mSqlTemplate.selectByColumn(column, value);
        System.out.println(sql);
        return findFirst(sql);
    }

    public M findFirstByColumns(SelectCondition[] conditions) {
        String sql = mSqlTemplate.selectByColumns(conditions);
        System.out.println(sql);
        return findFirst(sql);
    }

    public void setSecretColumns(String[] names) {
        mSecretColumns = names;
    }

    public List<M> findAll(){
        return find(mSqlTemplate.selectAll());
    }

    public int deleteByColumn(String column,Object value){
        return Db.update(mSqlTemplate.deleteByColumn(column,value));
    }

    public int deleteByColumns(SelectCondition[] conditions){
        return Db.update(mSqlTemplate.deleteByColumns(conditions));
    }

}
